//
//  BKClassifyGoodsListViewController.m
//  bestkeep
//
//  Created by utouu_mhm on 16/11/15.
//  Copyright © 2016年 utouu. All rights reserved.
//

#import "BKClassifyGoodsListViewController.h"
#import "BKTopScrollViewHeaderView.h"
#import "BKClassifyCommon.h"
#import "BKCustomSwitchBtn.h"
#import "BKManyClassfiyKindsHeaderView.h"
#import "BKRecordGoodsListStatusModel.h"
#import "BKClassifyCommon.h"
#import "MJExtension.h"
#import "BKManyClassfiyKindsModel.h"
#import "MJRefresh.h"
#import "BKRecordCurrentModel.h"
#import "BKScrollViewHeaderModel.h"
#import "Mediator.h"
#import "Mediator+BKGD.h"
#import "Mediator+BKMy.h"
#import "SystemMessageVC.h"
#import "Mediator+BKSearch.h"
#import "BKHomeClassifyCollectionView.h"
#import "BKDoubleCollectionViewCell.h"
#import "BKSingleCollectionViewCell.h"

@interface BKClassifyGoodsListViewController ()<BKCustomSwitchBtnDelegate,BKManyClassfiyKindsHeaderViewDelegate, BKHomeClassifyCollectionViewDelegate, BKTopScrollViewHeaderViewDelegate, UIScrollViewDelegate, UITextFieldDelegate, UISearchBarDelegate>

@property (nonatomic, strong) BKCustomSwitchBtn *changeShowTypeBtn;//转换cell布局的Btn
@property (nonatomic, strong) BKHomeClassifyCollectionView *collectionView;
@property (nonatomic, strong) BKManyClassfiyKindsHeaderView *headerView;//头部试图
@property (nonatomic, strong) BKRecordGoodsListStatusModel *curStatus; //记录当前页的状态
@property (nonatomic, strong) UIButton *backToTopBtn;//返回顶部按钮
@property (nonatomic, strong) BKRecordCurrentModel *currentModel;//记录加载数据的模型
@property (nonatomic, strong) NSArray *totalArray;
@property (nonatomic, strong) NSMutableArray *addUpArray;
@property (nonatomic, assign) BOOL isOverScreen; //数据展示超过一屏
@property (nonatomic, strong) BKTopScrollViewHeaderView *scrollHeader;
@property (nonatomic, strong) NSArray *titleNameArray;
@property (nonatomic, assign) CGFloat lastcontentoffset;
@property (nonatomic, strong) UIScrollView *backScrollView;
@property (nonatomic, strong) NSMutableArray *collectionArray; //collectionview的数组
@property (nonatomic, assign) GoodsListTableShowType goodsShowType;
@property (nonatomic, assign) NSInteger curPage;
@property (nonatomic, assign) NSInteger fromWhere;
@property (nonatomic, strong) ExceptionView *exceptionView;
@property (nonatomic, strong) UIView *badgeView;
@property (nonatomic, assign) BOOL isFirst;
@property (nonatomic, assign) BOOL isRefresh;
@property (nonatomic, assign) BOOL isIndicator;
@property (nonatomic, strong) UITextField *searchTextField;
@property (nonatomic, assign) NSInteger orderKeyIndex;
@property (nonatomic, strong) UIImageView * imgV;
@property (nonatomic, strong) UIImageView * imageV;
@property (nonatomic, strong) UIView *titleView;
@property (nonatomic, strong) UIView *searchBarView;
@end

@implementation BKClassifyGoodsListViewController

-(void)viewDidLoad{
    [super viewDidLoad];
    self.view.backgroundColor = ThemeBackgroundColor;
    _isFirst = YES;
    _isRefresh = YES;
    _orderKeyIndex = 0;
    _curPage = 0;
    self.goodsShowType = singleLineShowDoubleGoods;

    NSDictionary *bodyDic = @{@"currentPage": [NSString stringWithFormat:@"%ld",(long)_curPage],
                              @"channelType": ((_channelType == nil) ? @"" : _channelType),
                              @"categoryId": ((_categoryId == nil) ? @"" : _categoryId),
                              @"keyWord": ((_keyWord == nil) ? @"" : _keyWord),
                              @"filterTerms": ((_filterTerms == nil) ? @"" : _filterTerms),
                              @"order_key": ((_orderKey == nil) ? @"" : _orderKey),
                              @"sort_name": ((_order == nil) ? @"" : _order)};
    self.curStatus = [BKRecordGoodsListStatusModel mj_objectWithKeyValues:bodyDic];

    [self createNavigationItem];
    [self initializeComponent];
}

-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    
    _titleView.hidden = NO;
    if (self.navigationItem.rightBarButtonItem == nil) {
        [self setupBarButtonItem];
    }
    
    [BKClassifyCommon haveNewInformation:self.badgeView];
    
    [self setImgvFrame];
}

#pragma mark - 创建navigationbarItem
-(void)createNavigationItem{
//    [self setupBarButtonItem];
    [self setupSearchView];
}

#pragma mark - 设置消息按钮
-(void)setupBarButtonItem{
    //返回箭头
    UIBarButtonItem *leftBarButton = [[UIBarButtonItem alloc] initWithImage:[[UIImage imageNamed:@"naviBack"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] style:UIBarButtonItemStylePlain target:self action:@selector(popNavigation)];
    [leftBarButton setImageInsets:UIEdgeInsetsMake(5, -1, 0, 1)];
    self.navigationItem.leftBarButtonItem = leftBarButton;
    //消息
    UIButton *rightBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    rightBtn.frame = CGRectMake(0, 0, 28, 23);
    UIImageView *imageView = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"消息中心icon"]];
    imageView.frame = CGRectMake(5, 0, 23, 23);
    [rightBtn addSubview:imageView];
    [rightBtn addTarget:self action:@selector(infoAction) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *rightItem = [[UIBarButtonItem alloc]initWithCustomView:rightBtn];
    self.navigationItem.rightBarButtonItem = rightItem;
    //消息红点
    self.badgeView = [[UIView alloc]initWithFrame:CGRectMake(17, 0, 6, 6)];
    self.badgeView.layer.cornerRadius = 3;
    self.badgeView.layer.masksToBounds = YES;
    self.badgeView.backgroundColor = [UIColor redColor];
    [imageView addSubview:self.badgeView];
}

-(void)popNavigation{
    [self.navigationController popToRootViewControllerAnimated:YES];
}

-(void)infoAction{
    NSDictionary *dict = [[Mediator sharedInstance] BKMyUserInfo];
    NSNumber *logIn = dict[@"BKMyUserIsLoginKey"];
    if ([logIn isEqualToNumber:@1]) {
        [self.navigationController pushViewController:[[SystemMessageVC alloc]init] animated:YES];
    }else{
        [[Mediator sharedInstance] userGoToLoginFromOrignalController:self finishBlock:^{
            
        }];
    }
}

#pragma mark - 设置搜索框
-(void)setupSearchView{
    _titleView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth - 98, 30)];
    _titleView.layer.cornerRadius = 15;
    _titleView.layer.masksToBounds = YES;
    [_titleView setBackgroundColor:[UIColor clearColor]];
    
    _searchBarView = [[UIView alloc]initWithFrame:CGRectMake(4, 0, ScreenWidth-86, 30)];
    _searchBarView.backgroundColor = RGBACOLOR(218, 218, 218, 0.5);
    _searchBarView.layer.masksToBounds = YES;
    _searchBarView.layer.cornerRadius = 15;
    [_titleView addSubview: _searchBarView];
    
    _searchTextField = [[UITextField alloc]initWithFrame:CGRectMake(0, 0, ScreenWidth-86, 30)];
    _searchTextField.backgroundColor = [UIColor clearColor];//RGBACOLOR(218, 218, 218, 0.5);
    _searchTextField.text = self.curStatus.keyWord;
    _searchTextField.font = [UIFont systemFontOfSize:14];
    _searchTextField.delegate = self;
    _searchTextField.placeholder = @"请输入商品名称";

    [_searchTextField setValue:RGB(178, 178, 178) forKeyPath:@"_placeholderLabel.textColor"];
    _searchTextField.returnKeyType = UIReturnKeySearch;
    _searchTextField.textAlignment = NSTextAlignmentCenter;
    _imgV = [[UIImageView alloc]init];
    [self setImgvFrame];
    [_titleView addSubview:_imgV];
    
    [_searchBarView addSubview:_searchTextField];
    self.navigationItem.titleView = _titleView;
    [BKClassifyCommon haveNewInformation:self.badgeView];
    if ([_searchTextField.text isEqualToString:@""]) {
        UIControl * gotoSeaarchControl = [[UIControl alloc] initWithFrame:_searchTextField.bounds];
        [gotoSeaarchControl addTarget:self action:@selector(searchAction) forControlEvents:UIControlEventTouchUpInside];
        [_searchTextField addSubview:gotoSeaarchControl];
    }
}

-(void)setImgvFrame{
    [_imgV removeFromSuperview];
    NSString *holder = [_searchTextField.text isEqualToString:@""]?@"请输入商品名称": _searchTextField.text;
    
    CGSize size = [self sizeWithContentString:holder textFont:[UIFont systemFontOfSize:14] size:CGSizeMake(1000, 15)];
    CGFloat searchWith = size.width;
    CGFloat x = (SCREENWIDTH - searchWith) * 0.5 - 14 - 5;
    _imgV.frame = CGRectMake(x - 43, 8, 14, 14);
    _imgV.image = [UIImage imageNamed:@"searchIcon"];
    [_titleView addSubview:_imgV];
}

-(CGSize)sizeWithContentString:(NSString *)content textFont:(UIFont *)font size:(CGSize)contentSize{
    
    NSDictionary * fontDict = [NSDictionary dictionaryWithObjectsAndKeys:font,NSFontAttributeName,nil];
    CGRect rect = [content boundingRectWithSize:contentSize options:NSStringDrawingUsesLineFragmentOrigin attributes:fontDict context:nil];
    
    return rect.size;
}

-(void)searchAction{
    UIViewController *search = [[Mediator sharedInstance]BKSearchViewController];
    search.navigationItem.hidesBackButton = YES;
    [self.navigationController pushViewController:search animated:NO];
}

-(BOOL)textFieldShouldBeginEditing:(UITextField *)textField{
    [_imgV removeFromSuperview];
    _searchTextField.frame = CGRectMake(34, 0, ScreenWidth-56, 30);
    _imageV = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"searchIcon"]];
    _imageV.frame = CGRectMake(7.5, 8, 14, 14);
    _searchTextField.textAlignment = NSTextAlignmentLeft;
    if (![_searchBarView.subviews containsObject:_imageV]) {
        [_searchBarView addSubview:_imageV];
    }
    return YES;
}

-(BOOL)textFieldShouldReturn:(UITextField *)textField{
    
    if ([textField.text isEqualToString:@""]) {
        [textField resignFirstResponder];
        
        _imageV.hidden = YES;
        _searchTextField.frame = CGRectMake(0, 0, ScreenWidth-86, 30);
        _searchTextField.textAlignment = NSTextAlignmentCenter;
        [self setImgvFrame];
        
        return NO;
    }
    
    _searchTextField.text = textField.text;
    self.curStatus.keyWord = _searchTextField.text;
    if (![_searchTextField.text isEqualToString:@""]) {
        NSString *documentsPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)firstObject];
        NSString *filePath = [documentsPath stringByAppendingPathComponent:@"searchKey.plist"];
        
        NSMutableArray *dataArr = [NSMutableArray arrayWithContentsOfFile:filePath];
        NSMutableArray *itemArr = [NSMutableArray arrayWithArray:dataArr];
        for (NSString *string in itemArr) {
            if ([string isEqualToString:textField.text]) {
                [dataArr removeObjectAtIndex:[itemArr indexOfObject:string]];
            }else{
                
            }
        }
        [dataArr addObject:_searchTextField.text];
        [dataArr writeToFile:filePath atomically:YES];
    }
    
    
    if (_orderKeyIndex == 0) {
        self.curStatus.filterTerms = @"-1";
    }else if (_orderKeyIndex == 1){
        self.curStatus.filterTerms = @"0";
    }else if (_orderKeyIndex == 2){
        self.curStatus.filterTerms = @"1";
    }
    
    _isIndicator = YES;
    
    [textField resignFirstResponder];
    _imageV.hidden = YES;
    _searchTextField.frame = CGRectMake(0, 0, ScreenWidth-86, 30);
    _searchTextField.textAlignment = NSTextAlignmentCenter;
    [self setImgvFrame];
    
//    [self requestInformationWithFilterTerms:self.curStatus.filterTerms categotyId:@"" channelType:@"" orderKey:@"" currentPage:0 keyWord:textField.text order:@""];
    //2017.2.13
    [self loadDataWithCurrentStatus:nil keyWord:textField.text];
    
    return YES;
}

#pragma mark - 初始化UI
-(void)initializeComponent {
    
    self.edgesForExtendedLayout = UIRectEdgeNone;
    
    self.scrollHeader = [[BKTopScrollViewHeaderView alloc] init];
    self.scrollHeader.delegate = self;
    self.scrollHeader.hidden = YES;
    
    self.headerView = [[BKManyClassfiyKindsHeaderView alloc] init];
    self.headerView.HeaderViewDelegate = self;
    self.headerView.hidden = YES;
    
    _backScrollView = [[UIScrollView alloc] init];
    _backScrollView.pagingEnabled = YES;
    _backScrollView.showsVerticalScrollIndicator = NO;
    _backScrollView.showsHorizontalScrollIndicator = NO;
    _backScrollView.delegate = self;
    _backScrollView.bounces = NO;
    
    
    if ([self.classifyType isEqualToString:@"0"] || self.classifyType == nil) {
        self.scrollHeader.frame = CGRectMake(0, 0, ScreenWidth, 35);
        self.headerView.frame = CGRectMake(0, 35, ScreenWidth, 35);
        _backScrollView.frame = CGRectMake(0, 69.5, ScreenWidth, ScreenHeight-69.5 - 64);
        _backScrollView.scrollEnabled = YES;
        //请求头的标题的数组
        [self requestTilteNameArrayWithChanelType:self.curStatus.channelType categoryId:self.curStatus.categoryId];
    }else{
        self.scrollHeader.frame = CGRectZero;
        self.headerView.frame = CGRectMake(0, 0, ScreenWidth, 35);
        _backScrollView.frame = CGRectMake(0, 34.5, ScreenWidth, ScreenHeight-34.5 - 64);
        _backScrollView.scrollEnabled = NO;
        _headerView.hidden = NO;
        _scrollHeader.hidden = NO;
        
//        [self requestInformationWithFilterTerms:_filterTerms categotyId:_categoryId channelType:_channelType orderKey:_orderKey currentPage:[_currentPage integerValue] keyWord:_keyWord order:_order];
        //2017.2.13
        [self loadDataWithCurrentStatus:self.curStatus keyWord:nil];
    }
    
    UICollectionViewFlowLayout *layout1 = [[UICollectionViewFlowLayout alloc]init];
    self.collectionView = [[BKHomeClassifyCollectionView alloc]initWithFrame:CGRectMake(0, 0, CGRectGetWidth(_backScrollView.frame), CGRectGetHeight(_backScrollView.frame)) collectionViewLayout:layout1];
    self.collectionView.myDelegate = self;
    [_backScrollView addSubview:self.collectionView];
    _collectionArray = [NSMutableArray array];
    [_collectionArray addObject:self.collectionView];
    
    self.collectionView.isNoData = NO;
    [self refreshData];
    self.collectionView.showType = self.goodsShowType;
    
    [self.view addSubview:self.scrollHeader];
    [self.view addSubview:self.headerView];
    [self.view addSubview:_backScrollView];
    
    //更换展示商品列表的按钮
    _changeShowTypeBtn = [[BKCustomSwitchBtn alloc]initWithFrame:CGRectZero];
    _changeShowTypeBtn.hidden = YES;
    _changeShowTypeBtn.selected = YES;
    _changeShowTypeBtn.myDelegate = self;
    [_changeShowTypeBtn setDragEnable:YES];
    [_changeShowTypeBtn setAdsorbEnable:YES];
    _changeShowTypeBtn.frame = CGRectMake(ScreenWidth-40, _backScrollView.frame.origin.y + 5, 30, 30);
    [_changeShowTypeBtn addTarget:self action:@selector(changeShowTypeHome:) forControlEvents:UIControlEventTouchUpInside];
    [_changeShowTypeBtn setBackgroundImage:[UIImage imageNamed:@"商品列表样式1"] forState:UIControlStateNormal];
    [_changeShowTypeBtn setBackgroundImage:[UIImage imageNamed:@"商品列表样式2"] forState:UIControlStateSelected];
    [self.view addSubview:_changeShowTypeBtn];
    
    _backToTopBtn=[[UIButton alloc]initWithFrame:CGRectMake(ScreenWidth-50,ScreenHeight-110, 30,30)];
    _backToTopBtn.hidden = YES;
    _backToTopBtn.backgroundColor=[UIColor clearColor];
    [_backToTopBtn setBackgroundImage:[UIImage imageNamed:@"backTopIcon"] forState:(UIControlStateNormal)];
    [_backToTopBtn addTarget:self action:@selector(backToTopBtnTouchHome:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:_backToTopBtn];
    self.lastcontentoffset = 0;
    
    [BKClassifyCommon haveNewInformation:self.badgeView];
}

#pragma mark - 更改展示样式
-(void)changeShowTypeHome:(UIButton *)btn{
    if (btn.isSelected) {
        btn.selected = NO;
        self.goodsShowType = singleLineShowOneGoods;
    } else {
        btn.selected = YES;
        self.goodsShowType = singleLineShowDoubleGoods;
    }
}

#pragma mark - 禁止切换btn位置在搜索条件栏上
-(void)btnCurrentLocationOrignalY:(CGFloat)orignalY begainPoint:(CGPoint)point{
    
    if (self.backScrollView.frame.origin.y > orignalY) {
        [UIView animateWithDuration:0.2 animations:^{
            self.changeShowTypeBtn.frame = CGRectMake(ScreenWidth-40, self.backScrollView.frame.origin.y + 5, 30, 30);
        }];
    }
}

#pragma mark - 请求列表数据
-(void)loadData{
//    [self requestInformationWithFilterTerms:self.curStatus.filterTerms categotyId:self.curStatus.categoryId channelType:self.curStatus.channelType orderKey:self.curStatus.order_key currentPage:1 keyWord:self.curStatus.keyWord order:self.curStatus.sort_name];
    //2017.2.13
    [self loadDataWithCurrentStatus:self.curStatus keyWord:nil];
}

-(void)loadDataWithCurrentStatus:(BKRecordGoodsListStatusModel *)goodsListStatus keyWord:(NSString*)keyWord{
    
    NSDictionary *paramDict = [[NSDictionary alloc] init];
    if (keyWord == nil) {
        paramDict = [self creatRequestDictWithFilterTerms: goodsListStatus.filterTerms categotyId: goodsListStatus.categoryId channelType: goodsListStatus.channelType orderKey: goodsListStatus.order_key currentPage: 1 keyWord: goodsListStatus.keyWord order: goodsListStatus.sort_name];
    }else{
        paramDict = [self creatRequestDictWithFilterTerms: self.curStatus.filterTerms categotyId: @"" channelType: @"" orderKey: @"" currentPage: 1 keyWord: keyWord order: @""];
    }
    
    if (_isFirst) {
        _isFirst = NO;
        [LoadingView loadingShoppingCartInView:self.collectionView];
    }
    
    if (_isIndicator) {
        _isIndicator = NO;
        [BKIndicationView showInView:self.view];
    }
    self.collectionView.isNoData = NO;
    [BKClassifyCommon getNewGoodsDetailClassifyTreeInfo:paramDict compeletion:^(id result, NSError *error) {
        
        if(self.exceptionView) {
            [self.exceptionView dismiss];
            self.exceptionView = nil;
        }
        
        if (result) {
            BKManyClassfiyKindsModel *model = result;
            _changeShowTypeBtn.hidden = NO;
            self.totalArray = model.list;
            
            _currentModel = [[BKRecordCurrentModel alloc]init];
            _currentModel.totalPage = model.totalPage;
            _currentModel.currentPage = model.currentPage;
            self.currentModel.list = model.list;
            self.changeShowTypeBtn.hidden = NO;
            self.currentModel = _currentModel;
        
            if (self.currentModel.currentPage >= model.totalPage) {
                [self.collectionView.mj_footer endRefreshingWithNoMoreData];
                self.collectionView.mj_footer = nil;
                if (self.isOverScreen) {
                    self.collectionView.isNoData = YES;
                }else{
                    self.collectionView.isNoData = NO;
                }
            }
            if (self.currentModel.list.count == 0) {
                
                _changeShowTypeBtn.hidden = YES;
                self.collectionView.isNoData = NO;
                
                ExceptionCodeType type = ExceptionCodeTypeNoNetwork;
                if ([self.keyWord isEqualToString:@""] || self.keyWord == nil) {
                    type = ExceptionCodeTypeEmptyPages;
                    self.exceptionView = [ExceptionView exceptionViewWithType:type];
                    ExceptionViewAction *retryAction = [ExceptionViewAction actionWithType:type handler:^(ExceptionViewAction *action) {
                        [_exceptionView dismiss];
                        _exceptionView = nil;
                        [self loadData];
                    }];
                    [self.exceptionView addAction:retryAction];
                    self.exceptionView.frame = CGRectMake(0, -64, self.view.frame.size.width, self.view.frame.size.height+64);
                }else{
                    type = ExceptionCodeTypeSearchIsEmpty;
                    self.exceptionView = [ExceptionView exceptionViewWithType:type];
                    [self.exceptionView showInView:self.view];
                }
                
                [self.exceptionView showInView:self.view];
            }
        }
        [LoadingView dismiss];
        [BKIndicationView dismiss];
    } failure:^(id result, NSError *error) {
        
        if (!_isRefresh) {
            _isRefresh = YES;
            _currentModel = nil;
            _collectionView.dataArray = nil;
            [_collectionView reloadData];
        }
        
        if(!self.exceptionView && error) {
            
            ExceptionCodeType type = ExceptionCodeTypeNoNetwork;
            if (error.code == -1009) {
                type = ExceptionCodeTypeNoNetwork;
            }else if (error.code == -1001){
                type = ExceptionCodeTypeRequestFailed;
            }else if (error.code == 502 || error.code == 404){
                type = ExceptionCodeTypeServerError;
            }else{
                type = ExceptionCodeTypeFailedToLoad;
            }
            self.exceptionView = [ExceptionView exceptionViewWithType:type];
            self.exceptionView.backgroundColor = [UIColor colorWithWhite:0.902 alpha:1.000];
            ExceptionViewAction *retryAction = [ExceptionViewAction actionWithType:type handler:^(ExceptionViewAction *action) {
                _isFirst = YES;
                [_exceptionView dismiss];
                _exceptionView = nil;
                [self loadData];
            }];
            [self.exceptionView addAction:retryAction];
            [self.exceptionView showInView:self.view];
            self.exceptionView.frame = CGRectMake(0, -64, self.view.frame.size.width, self.view.frame.size.height+64);
        }
        [LoadingView dismiss];
        [BKIndicationView dismiss];
    }];
    
    [self.collectionView.mj_footer endRefreshing];
    [self.collectionView.mj_header endRefreshing];
}

#pragma mark - 创建请求数组
-(NSDictionary *)creatRequestDictWithFilterTerms:(NSString *)filterTerms categotyId:(NSString *)categoryId channelType:(NSString *)channelType orderKey:(NSString *)orderKey currentPage:(NSInteger)page keyWord:(NSString *)keyWord order:(NSString *)order{
        
    switch ([filterTerms integerValue]) {
        case 0:
            orderKey = @"saledCount";
            order = @"";
            break;
            
        case 1:
            orderKey = @"newGoods";
            order = @"";
            break;
            
        case 2:
            orderKey = @"price";
            order = order;
            break;
            
        default:
            orderKey = @"";
            order = @"";
            break;
    }
    
    NSDictionary *bodyDic = @{@"currentPage":[NSString stringWithFormat:@"%ld",(long)page],
                              @"channelType": ((channelType == nil) ? @"" : channelType),
                              @"categoryId": ((categoryId == nil) ? @"" : categoryId),
                              @"keyWord": ((keyWord == nil) ? @"" : keyWord),
                              @"filterTerms": @"-1",
                              @"order_key": orderKey,
                              @"sort_name": order};
    
    return bodyDic;
}

#pragma mark - 总刷新
-(void)refreshData {
    
    MJRefreshGifHeader *header1 = [BKRefreshGifHeader headerWithRefreshingTarget:self refreshingAction:@selector(loadDownData)];
    self.collectionView.mj_header = header1;
    
    [self setUpFooter];
}

-(void)setUpFooter{
    //    MJRefreshAutoNormalFooter *footer = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadUpData)];
    //    self.collectionView.mj_footer = footer;
    //    self.collectionView.mj_footer.automaticallyHidden = YES;
    
    MJRefreshBackNormalFooter *footer = [MJRefreshBackNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadUpData)];
    footer.stateLabel.textColor = [UIColor lightGrayColor];
    footer.stateLabel.font = [UIFont systemFontOfSize:14];
    footer.arrowView.image = [UIImage imageNamed:@"BKGDPullDown"];
    UIActivityIndicatorView *loadingView = [footer valueForKeyPath:@"loadingView"];
    loadingView.hidesWhenStopped = YES;
    loadingView.color = RGB(42, 187, 155);
    [footer addSubview:loadingView];
    self.collectionView.mj_footer = footer;
    self.collectionView.mj_footer.automaticallyHidden = YES;
}

#pragma mark - 下拉刷新
-(void)loadDownData{
    _isRefresh = NO;
    
    [self setUpFooter];
    
    [self loadData];
}

#pragma mark - 上拉加载
-(void)loadUpData{
    _isRefresh = NO;
    
    self.collectionView.isNoData = NO;
    __weak typeof(self) weakSelf = self;
    
    NSDictionary * body_dic = [self creatRequestDictWithFilterTerms:self.curStatus.filterTerms categotyId:self.curStatus.categoryId channelType:self.curStatus.channelType orderKey:self.curStatus.order_key currentPage:self.currentModel.currentPage + 1 keyWord:self.curStatus.keyWord order:self.curStatus.sort_name];
    
    [BKClassifyCommon getNewGoodsDetailClassifyTreeInfo:body_dic compeletion:^(id result, NSError *error) {
        if(self.exceptionView) {
            [self.exceptionView dismiss];
            self.exceptionView = nil;
        }
        
        BKRecordCurrentModel *currentModel = self.currentModel;
        NSMutableArray *upArray = [NSMutableArray arrayWithArray:self.currentModel.list];
        BKManyClassfiyKindsModel *model = result;
        [upArray addObjectsFromArray:model.list];
        weakSelf.totalArray = upArray;
        currentModel.currentPage = model.currentPage;
        currentModel.totalPage = model.currentPage;
        currentModel.list = weakSelf.totalArray;
        self.currentModel = currentModel;
        
        [self isOverEntryScreenWithNum:weakSelf.totalArray.count showType:self.goodsShowType];
        
        if (_currentModel.currentPage >= model.totalPage) {
            if (self.isOverScreen) {
                self.collectionView.isNoData = YES;
                [_collectionView.mj_footer endRefreshingWithNoMoreData];
                _collectionView.mj_footer = nil;
            }else{
                self.collectionView.isNoData = NO;
            }
        }
        [LoadingView dismiss];
    } failure:^(id result, NSError *error) {
        if (!_isRefresh) {
            _isRefresh = YES;
            _collectionView.dataArray = nil;
            [_collectionView reloadData];
        }
        
        if(!self.exceptionView && error) {
            ExceptionCodeType type = ExceptionCodeTypeNoNetwork;
            if (error.code == -1009) {
                type = ExceptionCodeTypeNoNetwork;
            }else if (error.code == -1001){
                type = ExceptionCodeTypeRequestFailed;
            }else if (error.code == 502 || error.code == 404){
                type = ExceptionCodeTypeServerError;
            }else{
                type = ExceptionCodeTypeFailedToLoad;
            }
            self.exceptionView = [ExceptionView exceptionViewWithType:type];
            self.exceptionView.backgroundColor = [UIColor colorWithWhite:0.902 alpha:1.000];
            ExceptionViewAction *retryAction = [ExceptionViewAction actionWithType:type handler:^(ExceptionViewAction *action) {
                _collectionView.dataArray = [NSArray array];
                [_exceptionView dismiss];
                _exceptionView = nil;
                [self loadUpData];
            }];
            [self.exceptionView addAction:retryAction];
            [self.exceptionView showInView:self.view];
            self.exceptionView.frame = CGRectMake(0, -64, self.view.frame.size.width, self.view.frame.size.height+64);
        }
        [LoadingView dismiss];
    }];
    
    [self.collectionView.mj_header endRefreshing];
    [self.collectionView.mj_footer endRefreshing];
}

#pragma mark - 列表头的数组的请求
-(void)requestTilteNameArrayWithChanelType:(NSString *)channeltype categoryId:(NSString *)categoryId{
    self.fromWhere = 0;
    
    switch ([channeltype integerValue]) {
        case 1:
            channeltype = @"5";
            categoryId = @"1";
            
            break;
        case 2:
            channeltype = @"5";
            categoryId = @"2";
            break;
        case 3:
            channeltype = @"5";
            categoryId = @"3";
            break;
        case 4:
            channeltype = @"5";
            categoryId = @"4";
            break;
            
        default:
            channeltype = self.channelType;
            categoryId = self.categoryId;
            break;
    }
    
    if (_isFirst) {
        _isFirst = NO;
        [LoadingView loadingShoppingCartInView:self.view];
    }
    
    [BKClassifyCommon getTopClassWithCategoryType:channeltype categoryId:categoryId compeletion:^(id result, NSError *error) {
        
        if (result) {
            
            if(self.exceptionView) {
                [self.exceptionView dismiss];
                self.exceptionView = nil;
            }
            
            _headerView.hidden = NO;
            _scrollHeader.hidden = NO;
            BKScrollViewHeaderModel *model = result;
            NSMutableArray *array = [NSMutableArray array];
            for (NSDictionary *dict in model.list) {
                BKScrollViewHeaderFirst *first = [BKScrollViewHeaderFirst mj_objectWithKeyValues:dict];
                [array addObject:first];
            }
            
            self.titleNameArray = array;
            
        }
        [LoadingView dismiss];
    } failure:^(id result, NSError *error) {
        
        if(!self.exceptionView && error) {
            ExceptionCodeType type = ExceptionCodeTypeNoNetwork;
            if (error.code == -1009) {
                type = ExceptionCodeTypeNoNetwork;
            }else if (error.code == -1001){
                type = ExceptionCodeTypeRequestFailed;
            }else if (error.code == 502 || error.code == 404){
                type = ExceptionCodeTypeServerError;
            }else{
                type = ExceptionCodeTypeFailedToLoad;
            }
            self.exceptionView = [ExceptionView exceptionViewWithType:type];
            self.exceptionView.backgroundColor = [UIColor colorWithWhite:0.902 alpha:1.000];
            ExceptionViewAction *retryAction = [ExceptionViewAction actionWithType:type handler:^(ExceptionViewAction *action) {
                _isFirst = YES;
                [self requestTilteNameArrayWithChanelType:channeltype categoryId:categoryId];
            }];
            [self.exceptionView addAction:retryAction];
            [self.exceptionView showInView:self.view];
            self.exceptionView.frame = CGRectMake(0, -64, self.view.frame.size.width, self.view.frame.size.height+64);
        }
        [LoadingView dismiss];
    }];
}

#pragma mark - 创建滚动图的contentSize
-(void)createScroConfigWithArr:(NSArray *)nameArray{
    _backScrollView.contentSize = CGSizeMake(ScreenWidth *(nameArray.count), ScreenHeight - 70 - 64);
    for (UIView *view in _backScrollView.subviews) {
        [view removeFromSuperview];
    }
    [self addSubCollectionViewWithArray:nameArray];
}
//添加视图
-(void)addSubCollectionViewWithArray:(NSArray *)nameArray
{
    _collectionArray = [NSMutableArray array];
    for (NSInteger i = 0; i < nameArray.count; i ++) {
        UICollectionViewFlowLayout *layout1 = [[UICollectionViewFlowLayout alloc]init];
        BKHomeClassifyCollectionView *collection = [[BKHomeClassifyCollectionView alloc]initWithFrame:CGRectMake(ScreenWidth * i, 0, CGRectGetWidth(_backScrollView.frame), CGRectGetHeight(_backScrollView.frame)) collectionViewLayout:layout1];
        collection.myDelegate = self;
        [_backScrollView addSubview:collection];
        [_collectionArray addObject:collection];
    }
}

#pragma mark - 滚动头视图的代理方法
-(void)BKTopScrollViewHeaderView:(BKTopScrollViewHeaderView *)BKTopScrollViewHeaderView index:(NSInteger)index categroName:(NSString *)name{
    
    self.collectionView.isNoData = NO;
    [self.collectionView.mj_footer endRefreshing];
    [self.collectionView.mj_header endRefreshing];

    [self resetScrowViewContentOffsetWithValue:index];
    BKScrollViewHeaderFirst *model = self.titleNameArray[index];
    self.collectionView = self.collectionArray[index];
    [self refreshData];
    self.collectionView.showType = self.goodsShowType;
    self.scrollHeader.curPage = index;
    [self isOverEntryScreenWithNum:self.collectionView.dataArray.count showType:self.goodsShowType];
    
    if (self.collectionView.isNoData || (!self.isOverScreen && self.collectionView.dataArray.count!=0)) {
        [self.collectionView.mj_footer endRefreshingWithNoMoreData];
    }
    if (self.collectionView.isRequest) {
        
        self.curStatus.currentPage = index;
        self.curStatus.categoryId = model.categoryId;
        self.curStatus.sort_name = self.collectionView.order;
        self.curStatus.filterTerms = self.collectionView.searchCondition;
        self.totalArray = self.collectionView.dataArray;
        [self.headerView recordSearchConditionWithSearchCondition:self.collectionView.searchCondition order:self.collectionView.order];
        return;
    }
    
    //在没有页面已经加载的情况下，翻页进行重置
    self.curStatus.currentPage = index;
    if ([self.classifyType isEqualToString:@"0"] || self.classifyType == nil) {
        self.curStatus.categoryId = model.categoryId;
    }else{
        self.curStatus.categoryId = self.categoryId;
    }
    self.curStatus.sort_name = @"";
    self.curStatus.filterTerms = @"-1";
    if ([self.curStatus.channelType isEqualToString: @"1"]||[self.curStatus.channelType isEqualToString:@"2"]||[self.curStatus.channelType isEqualToString:@"3"]) {
   
    } else {
        self.curStatus.channelType = @"";
    }
    self.headerView.isRest = YES;
    //进入列表界面 通过categoryId进行搜索 category为nil
    if (self.fromWhere < 1) {
        _isFirst = YES;
        [self loadData];
    }
    self.fromWhere = 0;
}

#pragma mark - 列表返回顶部箭头方法
-(void)backToTopBtnTouchHome:(UIButton *)backBtn{
    [self pullDownShowNavigation];
    [self.collectionView scrollRectToVisible:CGRectMake(0, 0, 1, 1) animated:YES];
}

#pragma mark - navigation的隐藏
-(void)BKCollectionViewWithContentOffset:(CGPoint)ContentOffset{
    if( ContentOffset.y > 0 ) {
        [self pullUpHideSearchTitle];
    } else {
        [self pullDownShowNavigation];
    }
    self.lastcontentoffset=ContentOffset.y;
}

#pragma mark - 商品列表上滑隐藏 下滑显示
-(void)pullUpHideSearchTitle{
    _backScrollView.scrollEnabled = NO;
    [UIView animateWithDuration:0.2 animations:^{
        self.headerView.frame = CGRectMake(0, -80, ScreenWidth, 0);
        self.scrollHeader.frame = CGRectMake(0, -80, ScreenWidth, 0);
        self.backScrollView.frame = CGRectMake(0, 0, ScreenWidth, ScreenHeight- 64);
        self.collectionView.frame = CGRectMake(ScreenWidth * self.scrollHeader.curPage, 0, _backScrollView.frame.size.width, ScreenHeight - 64);
    }];
}

#pragma mark - 点击箭头视图上升的过程
-(void)pullDownShowNavigation{
    if ([self.classifyType isEqualToString:@"0"] || self.classifyType == nil) {
        _backScrollView.frame = CGRectMake(0, 70, ScreenWidth, ScreenHeight - 70 - 64);
        self.collectionView.frame = CGRectMake(ScreenWidth * self.scrollHeader.curPage, 0,_backScrollView.frame.size.width, _backScrollView.frame.size.height);
        [UIView animateWithDuration:0.2 animations:^{
            _scrollHeader.frame = CGRectMake(0, 0, ScreenWidth, 35);
            _headerView.frame = CGRectMake(0, 35, ScreenWidth, 35);
        } completion:^(BOOL finished) {
            _backScrollView.scrollEnabled = YES;
            self.changeShowTypeBtn.frame = CGRectMake(ScreenWidth-40, _backScrollView.frame.origin.y + 5, 30, 30);
        }];
    }else{
        _backScrollView.frame = CGRectMake(0, 34.5, ScreenWidth, ScreenHeight - 34.5 - 64);
        self.collectionView.frame = CGRectMake(0, 0, _backScrollView.frame.size.width, _backScrollView.frame.size.height);
        [UIView animateWithDuration:0.2 animations:^{
            _scrollHeader.frame = CGRectZero;
            _headerView.frame = CGRectMake(0, 0, ScreenWidth, 35);
        } completion:^(BOOL finished) {
            _backScrollView.scrollEnabled = NO;
            self.changeShowTypeBtn.frame = CGRectMake(ScreenWidth-40, _backScrollView.frame.origin.y + 5, 30, 30);
        }];
    }
}

#pragma mark - 列表返回顶部箭头
-(void)tableviewCntentOffset:(CGPoint)offset{
    [self.view bringSubviewToFront:_backToTopBtn];
    if (offset.y > _backScrollView.frame.size.height) {
        _backToTopBtn.hidden = NO;
    } else {
        _backToTopBtn.hidden = YES;
    }
}

#pragma mark -- 默认，热销，价格，新品点击方法
-(void)BKManyClassfiyKindsHeaderView:(BKManyClassfiyKindsHeaderView *)BKManyClassfiyKindsHeaderView index:(NSInteger)index{
    
    _orderKeyIndex = index;
    if (index == 0) {
        self.curStatus.filterTerms = @"-1";
    }else if (index == 1){
        self.curStatus.filterTerms = @"0";
    }else if (index == 2){
        self.curStatus.filterTerms = @"1";
    }
    self.collectionView.isRequest = NO;
    _isIndicator = YES;
    
    [self setUpFooter];
    
    [self loadData];
}

//#pragma mark - collectionview的点击方法
//-(void)BKCollectionViewWithIndexPath:(NSIndexPath *)indexPath{
//    BKManyClassfiySecondModel *secondModel = _totalArray[indexPath.row];
//    UIViewController *goodistVC = [[Mediator sharedInstance] BKGD_goodsDetailViewController:secondModel.goodsId saleTypes:secondModel.saleTypes];
//    [self.navigationController pushViewController:goodistVC animated:YES];
//}

#pragma mark - collectionview的点击方法
-(void)BKCollectionViewWithIndexPath:(NSIndexPath *)indexPath{
    
    _titleView.hidden = YES;
    self.navigationItem.rightBarButtonItem = nil;
    self.badgeView = nil;
    
    BKManyClassfiySecondModel *secondModel = _totalArray[indexPath.row];
    CGRect frame = CGRectZero;
    if (self.goodsShowType == singleLineShowDoubleGoods) {
        BKDoubleCollectionViewCell *cell = (BKDoubleCollectionViewCell *)[self.collectionView cellForItemAtIndexPath:indexPath];
        frame = [self.collectionView convertRect:cell.frame toView:[UIApplication sharedApplication].keyWindow];
    }else{
        BKSingleCollectionViewCell *cell = (BKSingleCollectionViewCell *)[self.collectionView cellForItemAtIndexPath:indexPath];
        CGRect goodsFrame = [cell convertRect:cell.goodsImgeView.frame toView:cell.superview];
        frame = [self.collectionView convertRect:goodsFrame toView:[UIApplication sharedApplication].keyWindow];
    }
    
    [self goodsDetailAnimationWithFrame:frame goodsId:secondModel.goodsId saleTypes:secondModel.saleTypes goodsCoverImg:secondModel.goodsCoverImg];
}

/**
 跳转到详情页动画的方法

 @param frame 当前商品的frame
 @param goodsId 商品id
 @param saleTypes 营销参数
 @param goodsCoverImg 商品图片
 */
-(void)goodsDetailAnimationWithFrame:(CGRect)frame goodsId:(NSString*)goodsId saleTypes:(id)saleTypes goodsCoverImg:(NSString*)goodsCoverImg{
    CGFloat x = frame.origin.x;
    if (x > 0) {
        x -= 30;
    }else{
        x += 30;
    }
    CGRect rect = CGRectMake(x, frame.origin.y-98.5, frame.size.width, frame.size.height);
    UIImageView *imageview = [[UIImageView alloc] initWithFrame:rect];
    imageview.image = [CacheImage imageFromKey:goodsCoverImg];
    imageview.contentMode = UIViewContentModeScaleAspectFill;
    imageview.userInteractionEnabled = YES;
    UIView *maskView = [[UIView alloc] initWithFrame:CGRectMake(0, 64, SCREENWIDTH, ScreenHeight)];
    maskView.backgroundColor = [UIColor whiteColor];
    [maskView addSubview:imageview];
    [[UIApplication sharedApplication].keyWindow addSubview:maskView];
    
    [UIView animateWithDuration:0.3 animations:^{
        imageview.frame = CGRectMake(0, 0, SCREENWIDTH, SCREENWIDTH);
    } completion:^(BOOL finished) {
        if (maskView) {
            [maskView removeFromSuperview];
        }
        UIViewController *goodistVC = [[Mediator sharedInstance] BKGD_goodsDetailViewController:goodsId saleTypes:saleTypes goodsCoverImg:goodsCoverImg];
        [self.navigationController pushViewController:goodistVC animated:NO];
    }];
}

#pragma mark - 价格升降序的代理方法
-(void)BKManyClassfiyKindsHeaderView:(BKManyClassfiyKindsHeaderView *)BKManyClassfiyKindsHeaderView oderWay:(NSString *)oderWay{
    
    self.curStatus.filterTerms = @"2";
    self.curStatus.sort_name = oderWay;
    self.collectionView.isRequest = NO;
    [self loadData];
}

#pragma mark - set方法
-(void)setTotalArray:(NSArray *)totalArray{
    _totalArray = totalArray;
    self.collectionView.dataArray = _totalArray;
}

-(void)setGoodsShowType:(GoodsListTableShowType)goodsShowType{
    _goodsShowType = goodsShowType;
    self.collectionView.showType = _goodsShowType;
}

-(void)setCurPage:(NSInteger)curPage{
    _curPage = curPage;
    self.curStatus.currentPage = _curPage;
}

-(void)setTitleNameArray:(NSArray *)titleNameArray{
    _titleNameArray = titleNameArray;
    int index = 0;
    NSMutableArray *mutArray = [NSMutableArray array];
    for (int i = 0; i < titleNameArray.count; i ++) {
        BKScrollViewHeaderFirst *model = titleNameArray[i];
        if (![self.curStatus.categoryId isEqualToString:@""] && self.curStatus.categoryId != nil) {
            if ([model.categoryId isEqualToString:_categoryId]) {
                index = i;
                self.fromWhere = 2;
            }
        }
        [mutArray addObject:model.name];
    }
    
    self.scrollHeader.nameArray = mutArray;
    [self createScroConfigWithArr:mutArray];
    if (self.fromWhere > 0) {
        self.scrollHeader.curPage = index;
        self.curPage = index;
    }else{
        self.curPage = index;
        BKScrollViewHeaderFirst *model = titleNameArray[0];
        self.curStatus.categoryId = model.categoryId;
        if (model.selected) {
            [self BKTopScrollViewHeaderView:self.scrollHeader index:0 categroName:mutArray[0]];
        }
    }
    [self loadData];
}

-(void)setCurrentModel:(BKRecordCurrentModel *)currentModel{
    _currentModel = currentModel;
    _totalArray = currentModel.list;
    self.collectionView = self.collectionArray[self.curStatus.currentPage];
    self.collectionView.showType = self.goodsShowType;
    self.collectionView.searchCondition = self.curStatus.filterTerms;
    self.collectionView.order = self.curStatus.sort_name;
    self.collectionView.isRequest = YES;
    self.collectionView.dataArray = _currentModel.list;
    if ([[UIDevice currentDevice].systemName floatValue] < 8.0) {
        [self.scrollHeader changeScroviewContentOffset];
    }
    [self isOverEntryScreenWithNum:self.currentModel.list.count showType:self.goodsShowType];
}

-(void)setCollectionArray:(NSMutableArray *)collectionArray{
    _collectionArray = collectionArray;
    _collectionView.dataArray = _totalArray;
}

#pragma mark - UIScrollViewDelegate 滑动视图代理
-(void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView{
    [self.collectionView.mj_header endRefreshing];
    [self.collectionView.mj_footer endRefreshing];
    CGPoint point = scrollView.contentOffset;
    CGFloat offsetX = point.x;
    int curPage = offsetX/ScreenWidth;
    self.scrollHeader.curPage = curPage;
    self.curPage = curPage;
}

-(void)resetScrowViewContentOffsetWithValue:(NSInteger)value{
    self.curPage = (int)value;
    CGPoint point = CGPointMake(value * ScreenWidth, 0);
    [self.backScrollView setContentOffset:point animated:NO];
}

#pragma mark - 判断是否超出一屏
-(void)isOverEntryScreenWithNum:(NSInteger)num showType:(GoodsListTableShowType)showType{
    int distance = 0;
    if (showType == singleLineShowDoubleGoods) {
        distance = ScreenHeight -35 -35 -64 - (num + 1)/2 * (ScreenWidth-5)/2.0 * 428/345;
    } else {
        distance = ScreenHeight -35-35-64 - num * 117;
    }
    
    if (distance >0) {
        self.isOverScreen = NO;
    } else {
        self.isOverScreen = YES;
    }
}

@end
